<?php
defined('IN_PHPCMS') or exit('No permission resources.');
pc_base::load_app_class('admin', 'admin', 0);
pc_base::load_sys_class('form', '', 0);
pc_base::load_sys_class('format', '', 0);
pc_base::load_app_func('global', 'goods');

class goods extends admin
{
    private $db;
    private $type;
    private $info;
    private $order;
    private $setting;
    private $goods_check;
    private $customize_type;
    private $customize;


    function __construct()
    {
        parent::__construct();
        $this->db = pc_base::load_model('goods_model');
        $this->type = pc_base::load_model('goods_type_model');
        $this->info = pc_base::load_model('goods_info_model');
        $this->order = pc_base::load_model('goods_order_model');
        $this->module_db = pc_base::load_model('module_model');
        $this->member_db = pc_base::load_model('member_model');
        $this->setting = pc_base::load_model('goods_setting_model');
        $this->goods_check = pc_base::load_model('goods_check_model');
        $this->customize_type = pc_base::load_model('goods_customize_type_model');
        $this->customize = pc_base::load_model('goods_customize_model');
    }

    public function init()
    {
        $show_pc_hash = 1;
        $page = isset($_GET['page']) && intval($_GET['page']) ? intval($_GET['page']) : 1;
        $infos = $this->db->listinfo(array(), 'id DESC', $page, '14');
        foreach ($infos as $key => $val) {
            if ($val['ship'] == 2) {
                $infos[$key]['reserve'] = $this->db->getGoodsNum($val['id']);
            }
        }
        $pages = $this->db->pages;
        include $this->admin_tpl('index');
    }

    /**
     * 订单列表
     */
    public function goods_order()
    {
        $show_pc_hash = 1;
        $page = isset($_GET['page']) && intval($_GET['page']) ? intval($_GET['page']) : 1;
        $infos = $this->order->listinfo(array(), 'id DESC', $page, '14');
        $pages = $this->order->pages;
        include $this->admin_tpl('order');
    }

    /**
     * 后台导出号码
     */
    public function goods_export_data()
    {
        $where['goods_id'] = trim($_GET['id']);
        $result = $this->info->select($where, '*');
        $dir = CACHE_PATH . 'qq/';
        $name = date('YmdHis', time()) . mt_rand(1000, 9999);
        $filename = $dir . $name . '.txt';
        if (!file_exists($filename)) {
            foreach ($result as $key => $val) {
                $data = rtrim($val['username'] . '----' . $val['password'] . '----' . $val['token'], '----');
                file_put_contents($filename, "{$data}\n", FILE_APPEND);
            }
        }
        if (!file_exists($filename)) {
            echo "文件找不到";
            exit ();
        }
        $file = fopen($filename, "r");
        Header("Content-type: application/octet-stream");
        Header("Accept-Ranges: bytes");
        Header("Accept-Length: " . filesize($filename));
        Header("Content-Disposition: attachment; filename=" . $name);
        echo fread($file, filesize($filename));
        fclose($file);
        unlink($filename);
        exit ();
    }

    public function goods_view()
    {
        $show_pc_hash = 1;
        $page = isset($_GET['page']) && intval($_GET['page']) ? intval($_GET['page']) : 1;
        if (!empty($_POST['keyword'])) {
            $where = "goods_id=" . intval(trim($_POST['goods_id'])) . " ";
            $keyword = trim($_POST["keyword"]);
            $where .= "AND username like '{$keyword}%'";
        } else {
            $where['goods_id'] = $_GET['id'];
        }
        $infos = $this->info->listinfo($where, 'id DESC', $page);
        $pages = $this->info->pages;
        include $this->admin_tpl('view');
    }

    /**
     * 添加信息
     */
    public function goods_add()
    {
        if (isset($_POST['action'])) {
            if (empty($_POST['goods_type'])) {
                showmessage(L('goods_type_empty', array(), 'goods'), HTTP_REFERER);
            }
            $data['name'] = trim($_POST['name']);
            $data['desc'] = trim($_POST['desc']);
            $data['goods_type'] = trim($_POST['goods_type']);
            $data['game'] = trim($_POST['game']);
            $data['friend_num'] = trim($_POST['friend_num']);
            $data['reserve'] = trim($_POST['reserve']);
            $data['price'] = trim($_POST['price']);
            $data['year_type'] = trim($_POST['year_type']);
            $data['type'] = trim($_POST['type']);
            $data['level_type'] = trim($_POST['level_type']);
            $data['num_type'] = trim($_POST['num_type']);
            $data['addtime'] = time();
            $data['updatetime'] = time();
            $result = $this->db->insert($data, true);
            if ($result) {
                showmessage(L('goods_add_success', array(), 'goods'), HTTP_REFERER);
            }
            showmessage(L('goods_add_error', array(), 'goods'), HTTP_REFERER);
        }
        $type = $this->type->select();
        include $this->admin_tpl('add');
    }

    /**
     * 删除数据
     */
    public function delete()
    {
        if ($_POST['submit'] == 'remove_all_selected') {
            $arr = array_values($_POST['ids']);
            $ids = implode(',', $arr);
            $where = "id IN($ids)";
            $result = $this->info->delete($where);
            if (empty($result)) {
                showmessage(L('goods_del_error', array(), 'goods'), HTTP_REFERER);
            }
            showmessage(L('goods_del_success', array(), 'goods'), HTTP_REFERER);
        }

    }



    /**
     * 更新信息
     */
    public function goods_edit()
    {
        if (isset($_POST['action'])) {
            $data['name'] = trim($_POST['name']);
            $data['desc'] = trim($_POST['desc']);
            $data['goods_type'] = trim($_POST['goods_type']);
            $data['game'] = trim($_POST['game']);
            $data['friend_num'] = trim($_POST['friend_num']);
            $data['ship'] = trim($_POST['ship']);
            $data['reserve'] = trim($_POST['reserve']);
            $data['price'] = trim($_POST['price']);
            $data['year_type'] = trim($_POST['year_type']);
            $data['type'] = trim($_POST['type']);
            $data['level_type'] = trim($_POST['level_type']);
            $data['num_type'] = trim($_POST['num_type']);
            $id = trim($_POST['id']);
            $result = $this->db->update($data, array('id' => $id));
            if ($result) {
                showmessage(L('goods_edit_success'), HTTP_REFERER);
            }
            showmessage(L('goods_edit_error'), HTTP_REFERER);
        }
        $result = $this->db->get_one(array('id' => trim($_GET['id'])));
        if (empty($result)) {
            showmessage(L('goods_empty'), HTTP_REFERER);
        }
        $type = $this->type->select();
        include $this->admin_tpl('edit');
    }

    public function goods_type()
    {
        $show_pc_hash = 1;
        $page = isset($_GET['page']) && intval($_GET['page']) ? intval($_GET['page']) : 1;
        $infos = $this->type->listinfo(array(), 'id DESC', $page, '14');
        $pages = $this->type->pages;
        include $this->admin_tpl('type');
    }

    /**
     * 下线产品列表
     */
    public function goods_info_del()
    {
        $result = $this->info->update(array('is_deny' => 3), array('id' => $_GET['id']));
        if (!empty($result)) {
            showmessage(L('goods_del_success'), HTTP_REFERER);
        }
        showmessage(L('goods_del_error'), HTTP_REFERER);
    }

    public function goods_type_add()
    {
        if (isset($_POST['action'])) {
            $data['name'] = $_POST['name'];
            $result = $this->type->insert($data, true);
            if ($result) {
                showmessage(L('goods_type_add_success'), HTTP_REFERER);
            }
            showmessage(L('goods_type_add_error'), HTTP_REFERER);
        }
        include $this->admin_tpl('type_add');
    }

    public function goods_type_edit()
    {
        if (isset($_POST['action'])) {
            $data['name'] = $_POST['name'];
            $result = $this->type->update($data, array('id' => trim($_POST['id'])));
            if ($result) {
                showmessage(L('goods_type_edit_success'), HTTP_REFERER);
            }
            showmessage(L('goods_type_edit_error'), HTTP_REFERER);
        }
        $result = $this->type->get_one(array('id' => trim($_GET['id'])));
        if (empty($result)) {
            showmessage(L('goods_empty'), HTTP_REFERER);
        }
        include $this->admin_tpl('type_edit');
    }

    public function goods_type_del()
    {
        $this->check_goods_type($_GET['id']);
        $result = $this->type->delete(array('id' => $_GET['id']));
        if (!empty($result)) {
            showmessage(L('goods_type_del_success'), HTTP_REFERER);
        }
        showmessage(L('goods_type_del_error'), HTTP_REFERER);
    }

    public function goods_del()
    {
        $result = $this->db->delete(array('id' => $_GET['id']));
        if (!empty($result)) {
            showmessage(L('goods_del_success'), HTTP_REFERER);
        }
        showmessage(L('goods_del_error'), HTTP_REFERER);
    }

    /**
     * 配置验证金额
     */
    public function goods_setting()
    {

        if ($_POST['setting'] == 'sub') {
            $this->setting->delete(true);
            foreach ($_POST['data'] as $key => $val) {
                $this->setting->insert(['name' => $key, 'value' => $val]);
            }
            showmessage('修改成功', HTTP_REFERER);
        }
        $result = $this->setting->select("", "*");
        $item = [];
        foreach ($result as $key => $value) {
            $item[$value['name']] = $value['value'];
        }
        include $this->admin_tpl('setting');
    }


    public function goods_cate()
    {
        $show_pc_hash = 1;
        $page = isset($_GET['page']) && intval($_GET['page']) ? intval($_GET['page']) : 1;
        $infos = $this->goods_check->listinfo(array(), 'id DESC', $page, '15');
        $pages = $this->goods_check->pages;
        include $this->admin_tpl('cate');
    }

    /**
     * 高级选号
     */
    public function goods_customize_type()
    {
        $show_pc_hash = 1;
        $page = isset($_GET['page']) && intval($_GET['page']) ? intval($_GET['page']) : 1;
        $infos = $this->customize_type->listinfo(array(), 'id DESC', $page, '15');
        $pages = $this->customize_type->pages;
        include $this->admin_tpl('customize_type');
    }

    /**
     * 高级分类选号添加
     */
    public function goods_customize_type_add()
    {
        if (isset($_POST['action'])) {
            $data['name'] = trim($_POST['name']);
            $data['sort'] = trim($_POST['sort']);
            $data['addtime'] = time();
            $data['updatetime'] = time();
            $result = $this->customize_type->insert($data, true);
            if ($result) {
                showmessage(L('goods_customize_type_add_success'), HTTP_REFERER);
            }
            showmessage(L('goods_customize_type_add_error'), HTTP_REFERER);
        }
        include $this->admin_tpl('customize_type_add');
    }

    /**
     * 修改高级选号分类
     */
    public function goods_customize_type_edit()
    {
        if (isset($_POST['action'])) {
            $data['name'] = trim($_POST['name']);
            $data['sort'] = trim($_POST['sort']);
            $data['addtime'] = time();
            $data['updatetime'] = time();
            $result = $this->customize_type->update($data, ['id' => trim($_POST['id'])]);
            if ($result) {
                showmessage(L('goods_customize_type_edit_success'), HTTP_REFERER);
            }
            showmessage(L('goods_customize_type_edit_error'), HTTP_REFERER);
        }
        $result = $this->customize_type->get_one(array('id' => trim($_GET['id'])));
        if (empty($result)) {
            showmessage(L('goods_empty'), HTTP_REFERER);
        }
        include $this->admin_tpl('customize_type_edit');
    }

    /**
     * 删除高级选号分类
     */
    public function goods_customize_type_delete()
    {
        if ($_GET['id']) {
            $where['type'] = trim($_GET['id']);
            $result = $this->customize->select($where, '*');
            if (!empty($result)) {
                showmessage(L('goods_customize_type_empty'), HTTP_REFERER);
            }
            $type = $this->customize_type->delete(['id' => trim($_GET['id'])]);
            if (empty($type)) {
                showmessage(L('goods_customize_type_delete_error'), HTTP_REFERER);
            }
            showmessage(L('goods_customize_type_delete_success'), HTTP_REFERER);
        }
    }

    /**
     * 高级选号列表
     */
    public function goods_customize()
    {
        $show_pc_hash = 1;
        $page = isset($_GET['page']) && intval($_GET['page']) ? intval($_GET['page']) : 1;
        $infos = $this->customize->listinfo(array(), 'id DESC', $page, '15');
        $type = $this->customize_type->select(array(), '*');
        $data = [];
        foreach ($infos as $key => $val) {
            foreach ($type as $k => $v) {
                $data[$key]['id'] = $val['id'];
                $data[$key]['name'] = $val['name'];
                $data[$key]['type'] = $val['type'];
                $data[$key]['sort'] = $val['sort'];
                $data[$key]['addtime'] = $val['addtime'];
                $data[$key]['updatetime'] = $val['updatetime'];
                if ($val['type'] == $v['id']) {
                    $data[$key]['type_name'] = $v['name'];
                }
            }
        }
        $pages = $this->customize->pages;
        include $this->admin_tpl('customize');
    }

    /**
     * 添加高级选号
     */
    public function goods_customize_add()
    {
        if (isset($_POST['action'])) {
            $data['name'] = trim($_POST['name']);
            $data['type'] = trim($_POST['type']);
            $data['data'] = trim($_POST['data']);
            $data['sort'] = trim($_POST['sort']);
            $data['addtime'] = time();
            $data['updatetime'] = time();
            $result = $this->customize->insert($data, true);
            if ($result) {
                showmessage(L('goods_customize_add_success'), HTTP_REFERER);
            }
            showmessage(L('goods_customize_add_error'), HTTP_REFERER);
        }
        $type = $this->customize_type->select('', '*');
        include $this->admin_tpl('customize_add');
    }

    /**
     * 编辑高级选号
     */
    public function goods_customize_edit()
    {
        if (isset($_POST['action'])) {
            $data['name'] = trim($_POST['name']);
            $data['type'] = trim($_POST['type']);
            $data['data'] = trim($_POST['data']);
            $data['sort'] = trim($_POST['sort']);
            $data['addtime'] = time();
            $data['updatetime'] = time();
            $result = $this->customize->update($data, ['id' => trim($_POST['id'])]);
            if ($result) {
                showmessage(L('goods_customize_edit_success'), HTTP_REFERER);
            }
            showmessage(L('goods_customize_edit_error'), HTTP_REFERER);
        }
        $result = $this->customize->get_one(array('id' => trim($_GET['id'])));
        if (empty($result)) {
            showmessage(L('goods_empty'), HTTP_REFERER);
        }
        $type = $this->customize_type->select('', '*');
        include $this->admin_tpl('customize_edit');
    }

    /**
     * 删除高级选号
     */
    public function goods_customize_delete()
    {
        $result = $this->customize->delete(['id' => $_GET['id']]);
        if (!empty($result)) {
            showmessage(L('goods_customize_delete_success'), HTTP_REFERER);
        }
        showmessage(L('goods_customize_delete_error'), HTTP_REFERER);
    }

    /**
     * 添加号码
     */
    public function goods_import()
    {
        if (isset($_POST['action'])) {
            $data = preg_split("/[\s,]+/", $_POST['content']);
            $goods_id = $_POST['goods_id'];
            $result = [];
            $token = '';
            foreach ($data as $key => $val) {
                $str_tmp = explode('----', $val);
                $result[$key]['goods_id'] = $goods_id;
                $result[$key]['username'] = $str_tmp[0];
                $result[$key]['password'] = $str_tmp[1];
                if (count($str_tmp) > 2) {
                    unset($str_tmp[0], $str_tmp[1]);
                    $arr = array_values($str_tmp);
                    foreach ($arr as $k => $v) {
                        $token .= $arr[$k] . '----' . $arr[$k + 1];
                        unset($arr[$k], $arr[$k + 1]);
                    }
                    $result[$key]['token'] = rtrim($token, '----');
                }
                $result[$key]['addtime'] = time();
                $result[$key]['updatetime'] = time();
            }
            foreach ($result as $key => $value) {
                $this->info->insert($value, true);
            }
            showmessage(L('goods_add_success'), HTTP_REFERER);
        }

        include $this->admin_tpl('import');
    }

    /**
     * 导出QQ通过浏览器下载
     */
    public function goods_export()
    {
        $data = $this->order->get_one(array('id' => trim($_GET['id'])));
        $dir = CACHE_PATH . 'bakup/';
        if ($data['type'] == 2){
            $result = $this->getCheck($data['goods_id']);
            $filename = $dir . $data['order_on'] . '.txt';
            foreach ($result as $key => $val) {
                file_put_contents($filename, "{$val}\n", FILE_APPEND);
            }
        }else{
            $result = $this->getGoodsList($data['goods']);
            $filename = $dir . $data['order_on'] . '.txt';
            if (!file_exists($filename)) {
                foreach ($result as $key => $val) {
                    $data = $val['username'] . '----' . $val['password'];
                    file_put_contents($filename, "{$data}\n", FILE_APPEND);
                }
            }
        }
        $name = date('YmdHis', time()) . '-' . mt_rand(1000, 9999) . '.txt';
        if (!file_exists($filename)) {
            echo "文件找不到";
            exit ();
        }
        $file = fopen($filename, "r");
        Header("Content-type: application/octet-stream");
        Header("Accept-Ranges: bytes");
        Header("Accept-Length: " . filesize($filename));
        Header("Content-Disposition: attachment; filename=" . $name);
        echo fread($file, filesize($filename));
        fclose($file);
        unlink($filename);
        exit ();
    }

    /**
     * 检查商品类型
     * @param $id
     */
    private function check_goods_type($id)
    {
        $type = $this->db->get_one(array('goods_type' => $id));
        if (!empty($type)) {
            showmessage(L('goods_type_empty'), HTTP_REFERER);
        }
    }

    /**
     * 获取检查QQ
     * @param $goods_id
     * @return mixed
     */
    private function getCheck($goods_id){
        $result = $this->goods_check->get_one(array('id'=>$goods_id));
        return preg_split("/[\s,]+/", $result['data']);
    }

    /**
     * 获取商品信息
     * @param $ids
     * @return mixed
     */
    private function getGoodsList($ids)
    {
        $where = "id IN($ids)";
        $result = $this->info->select($where, 'id,goods_id,is_deny,username,password');
        return $result;
    }
}